package com.wh.wisdomsite.xbox.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;

/**
 * @author arrow
 *
 */
public class SecCode {
	
	private static Random random = new Random();
	
	private static int verifySize = 5;
	
	//生成验证码 
	public static String drawImg(ByteArrayOutputStream output){
		String code = "";
		for(int i=0; i<4; i++){
			code += randomChar();
		}
		int width = 100;
		int height = 40;
		BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Algerian",Font.BOLD,25);
		Graphics2D g = bi.createGraphics();
		g.setFont(font);
		//设置颜色
		//生成随机颜色
		Random random = new Random();
		//设置背景
		g.setBackground(new Color(255,255,255));
		g.clearRect(0, 0, width, height);
		g.setColor(getRandColor(100, 160));  
        int fontSize = height-4;  
        g.setFont(font);  
        char[] chars = code.toCharArray();  
        for(int i = 0; i < 4; i++){  
            AffineTransform affine = new AffineTransform();  
            affine.setToRotation(Math.PI / 4 * random.nextDouble() * (random.nextBoolean() ? 1 : -1), (width / verifySize) * i + fontSize/2, height/2);  
            g.setTransform(affine);  
            Color color = new Color(random.nextInt(255)+1,random.nextInt(255)+1,random.nextInt(255)+1);
    		g.setColor(color);
            g.drawChars(chars, i, 1, ((width-10) / verifySize) * i + 5, height/2 + fontSize/2 - 10);  
        }
		
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", output);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return code;
	}
	
	//随机char
	private static char randomChar(){
		String s = "ABCDEFGHJKLMNPRSTUVWXYZ123456789";
		return s.charAt(random.nextInt(s.length()));
	}
	
	private static Color getRandColor(int fc, int bc) {  
        if (fc > 255)  
            fc = 255;  
        if (bc > 255)  
            bc = 255;  
        int r = fc + random.nextInt(bc - fc);  
        int g = fc + random.nextInt(bc - fc);  
        int b = fc + random.nextInt(bc - fc);  
        return new Color(r, g, b);  
    }
}
